package com.vitaf.cash.app.databinding

import androidx.databinding.BaseObservable
import com.vitaf.cash.app.BR
import org.json.JSONObject

/**
 * 通用型 DataBinding 实体类
 */
class GenericObservableModel : BaseObservable() {
    private val data = mutableMapOf<String, Any?>()

    fun <T> get(key: String): T? {
        @Suppress("UNCHECKED_CAST")
        return data[key] as? T
    }

    fun <T> get(key: String, defaultValue: T): T {
        @Suppress("UNCHECKED_CAST")
        return (data[key] as? T) ?: defaultValue
    }

    fun set(key: String, value: Any?) {
        if (data[key] != value) {
            data[key] = value
            notifyPropertyChanged(BR._all)
        }
    }

    fun setAll(newData: Map<String, Any?>) {
        data.putAll(newData)
        notifyPropertyChanged(BR._all)
    }

    // 直接设置JSON数据
    fun setJson(json: JSONObject?) {
        json?.let {
            val keys = json.keys()
            while (keys.hasNext()) {
                val key = keys.next()
                val value = json.get(key)
                if (data[key] != value) {
                    data[key] = value
                }
            }
            notifyPropertyChanged(BR._all)
        }
    }

    fun getString(key: String): String = get(key) ?: ""
    fun getString(key: String, defaultValue: String): String = get(key, defaultValue)

    fun getInt(key: String): Int = when (val value = data[key]) {
        is Number -> value.toInt()
        is String -> value.toIntOrNull() ?: 0
        else -> 0
    }

    fun getBoolean(key: String): Boolean = when (val value = data[key]) {
        is Boolean -> value
        is Number -> value.toInt() != 0
        is String -> value.toBoolean()
        else -> false
    }

    fun getImageUrl(key: String = "avatarUrl"): String = getString(key)
}